<?php

use Medoo\Medoo;

/**
 * https://medoo.in/api/new
 * http://www.querylist.cc/docs/guide/v4/http-client
 */
chdir(__DIR__);
require_once realpath('../..') . '/vendor/autoload.php';
$config = include '../database.php';
const BRAND = '特斯拉';
echo '爬虫开始' . PHP_EOL;

$db = new Medoo($config);
$db->delete('charger', ['brand' => BRAND]);

$client = new GuzzleHttp\Client();

function spider($type)
{
    global $client;
    global $db;
    $res = $client->request('GET', 'https://www.tesla.cn/all-locations?type=' . $type . '&bounds=3.52,73.40,53.33,135.230&deep&map=baidu');
    $html = (string)$res->getBody();
    $data = json_decode($html, true);

    foreach ($data as $item) {
        $phone = [];
        foreach ($item['sales_phone'] as $row) {
            $phone[] = $row['number'];
        }
        $note = implode(',', $item['location_type']);
        $db->insert('charger', [
            'brand' => BRAND,
            'province' => $item['province_state'],
            'city' => $item['city'],
            'title' => $item['title'],
            'address' => $item['address'],
            'tel' => implode(',', $phone),
            'lng' => $item['longitude'],
            'lat' => $item['latitude'],
            'note' => $note,
        ]);
        echo "{$item['title']}完成" . PHP_EOL;
    }

}

spider('supercharger');
spider('destination_charger');
echo '爬虫结束' . PHP_EOL;